/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package lt.ntec.danblog.server.blog.model.objectify;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;
import lt.ntec.danblog.server.core.model.Comment;
import lt.ntec.danblog.server.core.model.CommentDAO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Tadas
 */
class CommentListProxy implements InvocationHandler {

    private static final Logger LOG =
            LoggerFactory.getLogger(CommentListProxy.class);
    private List<Comment> comments;
    private final BlogPost blogPost;
    private final CommentDAO commentDAO;

    public static List<Comment> newInstance(BlogPost blogPost,
                                            CommentDAO commentDAO) {
        return (List<Comment>) Proxy.newProxyInstance(List.class.getClassLoader(),
                                                      new Class[]{List.class},
                                                      new CommentListProxy(
                blogPost, commentDAO));
    }

    private CommentListProxy(BlogPost blogPost, CommentDAO commentDAO) {
        this.blogPost = blogPost;
        this.commentDAO = commentDAO;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws
            IllegalAccessException, IllegalArgumentException,
            InvocationTargetException {

        if (comments == null) {
            LOG.debug("Creating proxy");
            comments = (List<Comment>) commentDAO.getListByParent(blogPost);
        }

        LOG.debug("Delegating call for " + method.getName());

        return method.invoke(comments, args);
    }
}
